package leetcode.method.dynamic_programming;

public class Program72WordMinDistance {

    public Program72WordMinDistance() {

    }

    public int minDistance(String word1, String word2) {
        int word1Length = word1.length();
        int word2Length = word2.length();
        if (word1Length == 0) {
            return word2Length;
        }
        if (word2Length == 0) {
            return word1Length;
        }

        int[][] dp = new int[word1Length + 1][word2Length + 1];

        for (int i = 1; i < word1Length + 1; i++) {
            dp[i][0] = i;
        }
        for (int j = 1; j < word2Length + 1; j++) {
            dp[0][j] = j;
        }

        for (int i = 1; i < word1Length + 1; i++) {
            for (int j = 1; j < word2Length + 1; j++) {
                int tmp = dp[i - 1][j - 1];
                if (word1.charAt(i - 1) != word2.charAt(j - 1)) {
                    tmp += 1;
                }
                dp[i][j] = Math.min(tmp, Math.min(dp[i][j - 1], dp[i - 1][j]) + 1);
                // dp[i - 1][j - 1] 最后一位直接替换
                // dp[i][j - 1], dp[i - 1][j]，最后一位插入一位
            }
        }

        return dp[word1Length][word2Length];
    }

    public static void main(String[] args) {
        Program72WordMinDistance myStack = new Program72WordMinDistance();
        System.out.println(myStack.minDistance("horse", "ros"));
        System.out.println(myStack.minDistance("intention", "execution"));
    }
}
